package com.qf.smsplatform.strategy.service;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.service.api.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: LeeRui
 * 2021/1/27 下午 9:47
 * 获取所有策略对象，并根据缓存要求依次执行
 **/
@Component
public class StrategyExecutor {

    //相当于将所有Spring构建的Strategy类型单例对象注入
    @Autowired
    private Map<String, Strategy> allStrategyObjects;

    @Autowired
    private CacheService cacheService;

    public void execute(StandardSubmit standardSubmit){
        //查询缓存中提供的执行顺序和要执行的策略
        String filters = cacheService.hget(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID(), "filters");
        //遍历全部策略对象，根据缓存顺序依次执行
        String[] strings = filters.split(",");
        for (String string : strings) {
            Strategy strategy = allStrategyObjects.get(string);
            //策略通过返回true，继续执行下一个策略
            boolean flag = strategy.strategy(standardSubmit);
            if (!flag){
                //策略执行失败，不能继续执行策略
                break;
            }
        }
    }
}
